package com.web.config;



import java.util.Properties;

import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
//import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jndi.JndiObjectFactoryBean;

import com.github.pagehelper.PageInterceptor;



/**
 * 
 * ClassName: AppConfig <br/>
 * Description: <应用配置类> Function:
 * 负责注册除Controller等web层以外的所有bean，包括aop代理，service层，dao层，缓存，等等 Reason: TODO ADD
 * REASON(可选). <br/>
 * date: 2017-8-10 下午4:36:03 <br/>
 * @author Sunxq
 * @version
 * @since JDK 1.8
 */
@Configuration
@MapperScan(basePackages={"com.jywl.mapper"},sqlSessionFactoryRef="sqlFactory")

public class DBConfig {
	@Bean(name="soaDataSource")
    public DataSource dataSource(){
        JndiObjectFactoryBean jndiObjectFactoryBean =new JndiObjectFactoryBean();
        jndiObjectFactoryBean.setJndiName("jdbc/jywl");
        jndiObjectFactoryBean.setResourceRef(true);
        jndiObjectFactoryBean.setProxyInterface(DataSource.class);
        try {
			jndiObjectFactoryBean.afterPropertiesSet();
		} catch (IllegalArgumentException | NamingException e) {
			e.printStackTrace();
		}
        return (DataSource) jndiObjectFactoryBean.getObject();  
    }
	@Bean
	public DataSourceTransactionManager txManager() {
		return new DataSourceTransactionManager(dataSource());
	}
	
	@Bean(name="sqlFactory")
	public SqlSessionFactory sqlSessionFactory() throws Exception {
		SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource());
		PageInterceptor pi = new PageInterceptor();
		Properties p = new Properties();
        p.setProperty("offsetAsPageNum", "true");
        p.setProperty("rowBoundsWithCount", "true");
        p.setProperty("reasonable", "true");
        pi.setProperties(p);
		sessionFactory.setPlugins(new Interceptor[]{pi});
		return sessionFactory.getObject();
	}

}
